package com.mars.admin.modules.admin;

import com.mars.admin.framework.common.Result;
import com.mars.admin.framework.exception.BusinessException;
import com.mars.admin.modules.post.entity.Topic;
import com.mars.admin.modules.post.service.ITopicService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 话题控制器
 *
 * @author Mars
 * @version 1.0
 * @date 2025-01-07
 */
@Slf4j
@RestController
@RequestMapping("/admin/topic")
@Tag(name = "后台话题管理", description = "话题相关接口")
public class AdminTopicController {

    @Autowired
    private ITopicService topicService;

    /**
     * 分页查询话题列表
     */
    /**
     * 分页查询话题列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询话题列表", description = "分页查询话题列表")
    public Result<Page<Topic>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "话题名称") @RequestParam(required = false) String name,
            @Parameter(description = "话题分类") @RequestParam(required = false) String category,
            @Parameter(description = "是否热门") @RequestParam(required = false) Integer isHot,
            @Parameter(description = "是否官方") @RequestParam(required = false) Integer isOfficial,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            Page<Topic> page = new Page<>(pageNumber, pageSize);
            // 使用带条件的分页查询方法
            Page<Topic> result = topicService.pageTopics(page, name, category, isHot, isOfficial, status);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询话题列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询所有话题列表
     */
    @GetMapping("/list")
    @Operation(summary = "查询所有话题列表", description = "查询所有话题列表")
    public Result<List<Topic>> list() {
        try {
            List<Topic> topics = topicService.list();
            return Result.success(topics);
        } catch (Exception e) {
            log.error("查询所有话题列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询话题详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询话题详情", description = "根据ID查询话题详情")
    public Result<Topic> getById(@Parameter(description = "话题ID") @PathVariable Long id) {
        try {
            Topic topic = topicService.getById(id);
            if (topic == null) {
                return Result.error("话题不存在");
            }
            return Result.success(topic);
        } catch (Exception e) {
            log.error("查询话题详情失败，话题ID：{}", id, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 创建话题
     */
    @PostMapping
    @Operation(summary = "创建话题", description = "创建新话题")
    public Result<Boolean> create(@RequestBody Topic topic) {
        try {
            boolean success = topicService.createTopic(topic);
            if (success) {
                return Result.success("创建成功", true);
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            log.error("创建话题失败，话题信息：{}", topic, e);
            if (e.toString().contains("Duplicate entry")){
                throw  new BusinessException("话题标题重复");
            }
            return Result.error("创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新话题
     */
    @PutMapping
    @Operation(summary = "更新话题", description = "更新话题信息")
    public Result<Boolean> update(@RequestBody Topic topic) {
        try {
            if (topic.getId() == null) {
                return Result.error("话题ID不能为空");
            }
            boolean success = topicService.updateTopic(topic);
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新话题失败，话题信息：{}", topic, e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除话题
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除话题", description = "根据ID删除话题")
    public Result<Boolean> delete(@Parameter(description = "话题ID") @PathVariable Long id) {
        try {
            boolean success = topicService.deleteTopic(id);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除话题失败，话题ID：{}", id, e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 根据分类查询话题列表
     */
    @GetMapping("/category/{category}")
    @Operation(summary = "根据分类查询话题", description = "根据分类查询话题列表")
    public Result<List<Topic>> getByCategory(@Parameter(description = "话题分类") @PathVariable String category) {
        try {
            List<Topic> topics = topicService.getTopicsByCategory(category);
            return Result.success(topics);
        } catch (Exception e) {
            log.error("根据分类查询话题失败，分类：{}", category, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询热门话题
     */
    @GetMapping("/hot")
    @Operation(summary = "查询热门话题", description = "查询热门话题列表")
    public Result<List<Topic>> getHotTopics(@Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Topic> topics = topicService.getHotTopics(limit);
            return Result.success(topics);
        } catch (Exception e) {
            log.error("查询热门话题失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询官方话题
     */
    @GetMapping("/official")
    @Operation(summary = "查询官方话题", description = "查询官方话题列表")
    public Result<List<Topic>> getOfficialTopics() {
        try {
            List<Topic> topics = topicService.getOfficialTopics();
            return Result.success(topics);
        } catch (Exception e) {
            log.error("查询官方话题失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 搜索话题
     */
    @GetMapping("/search")
    @Operation(summary = "搜索话题", description = "根据关键词搜索话题")
    public Result<List<Topic>> searchTopics(@Parameter(description = "搜索关键词") @RequestParam String keyword) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.error("搜索关键词不能为空");
            }
            List<Topic> topics = topicService.searchTopics(keyword.trim());
            return Result.success(topics);
        } catch (Exception e) {
            log.error("搜索话题失败，关键词：{}", keyword, e);
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 设置话题热门状态
     */
    @PutMapping("/{id}/hot")
    @Operation(summary = "设置话题热门状态", description = "设置话题是否为热门")
    public Result<Boolean> setHot(
            @Parameter(description = "话题ID") @PathVariable Long id,
            @Parameter(description = "是否热门：0-否，1-是") @RequestParam Integer isHot) {
        try {
            boolean success = topicService.setTopicHot(id, isHot);
            if (success) {
                return Result.success("设置成功", true);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置话题热门状态失败，话题ID：{}，热门状态：{}", id, isHot, e);
            return Result.error("设置失败：" + e.getMessage());
        }
    }

    /**
     * 设置话题官方状态
     */
    @PutMapping("/{id}/official")
    @Operation(summary = "设置话题官方状态", description = "设置话题是否为官方")
    public Result<Boolean> setOfficial(
            @Parameter(description = "话题ID") @PathVariable Long id,
            @Parameter(description = "是否官方：0-否，1-是") @RequestParam Integer isOfficial) {
        try {
            boolean success = topicService.setTopicOfficial(id, isOfficial);
            if (success) {
                return Result.success("设置成功", true);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置话题官方状态失败，话题ID：{}，官方状态：{}", id, isOfficial, e);
            return Result.error("设置失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除话题
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除话题", description = "根据ID列表批量删除话题")
    public Result<Boolean> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("话题ID列表不能为空");
            }
            boolean success = topicService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功", true);
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除话题失败，话题ID列表：{}", ids, e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
}